package logic

import (
	"context"
	"delivery/cache"
	"delivery/deliveryrpc/deliveryrpc"
	"delivery/deliveryrpc/internal/svc"
	"delivery/model"
	"delivery/pkg"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *deliveryrpc.RegisterRequest) (*deliveryrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	model.DB.Where("account", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("用户已注册请去登录")
	}
	if in.SenSmsCode == "" || in.CaptchaCode == "" {
		return nil, fmt.Errorf("验证码不能为空")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()
	if result != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	if len(in.Account) > 11 {
		return nil, fmt.Errorf("请输入正确的手机号")
	}
	s, _ := cache.Rdb.Get(cache.Ctx, "SenSms"+in.Account).Result()
	if s != in.SenSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	if in.Password == "" {
		return nil, fmt.Errorf("密码不能为空")
	}
	user = model.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}
	model.DB.Debug().Create(&user)
	return &deliveryrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
